package test2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//看一下 线程池 和 最后关闭谁
//为什么 Tcp不需要 创建 IP，port成员变量
public class TcpEchoServer {
    public ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            Socket clientSocket =  serverSocket.accept();
            Thread t = new Thread(()->{
                try {
                    processClient(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }

    private void processClient(Socket clientSocket) throws IOException {
        System.out.printf("客户端上线！[%s，%d]\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter= new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req=%s; resp=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(),
                        request, response);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            System.out.printf("客户端下线[%s,%d]！\n",clientSocket.getInetAddress(),clientSocket.getPort());
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer t = new TcpEchoServer(9090);
        t.start();
    }

}
